// 由于package.json中type为module，需要使用ESM语法
import jsonServer from "json-server";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import fs from "fs";

// 获取当前文件的目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const server = jsonServer.create();
const router = jsonServer.router(join(__dirname, "data.json"));
const middlewares = jsonServer.defaults();
const port = 3000;

// 确保data.json文件存在
const dataPath = join(__dirname, "data.json");
if (!fs.existsSync(dataPath)) {
    console.error("错误: data.json 文件不存在!");
    process.exit(1);
}

// 设置默认中间件（logger, static, cors等）
server.use(middlewares);

// 添加自定义中间件，处理CORS问题
server.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Access-Control-Allow-Methods", "*");
    next();
});

// 添加自定义路由
server.use(
    jsonServer.rewriter({
        "/api/*": "/$1",
        "/blog/:id": "/posts/:id",
        "/users/login": "/users",
    })
);

// 使用路由
server.use(router);

// 启动服务器
server.listen(port, () => {
    console.log(`JSON Server 正在运行，端口: ${port}`);
    console.log(`访问地址: http://localhost:${port}`);
    console.log(`可用API路径:`);
    console.log(`- http://localhost:${port}/users`);
    console.log(`- http://localhost:${port}/posts`);
    console.log(`- http://localhost:${port}/categories`);
    console.log(`- http://localhost:${port}/tags`);
    console.log(`- http://localhost:${port}/comments`);
});
